<?php
/**
 * 示例模型
 * @version 1.0
 * @author: HuangYu <992287102@qq.com>
 * @since: 2019/4/2 15:26
 * Class DemoModel
 * @package app\index\model
 */

namespace app\index\model;

use think\Model;

class DemoModel extends Model
{
    /**
     * 初始化
     * @author HuangYu
     * @since 2019/4/2
     */
    public static function init()
    {
        //前置添加
        self::event('before_insert', function ($model) {
            $model->create_time = date('Y-m-d H:i:s');
            $model->update_time = $model->create_time;

            return true;
        });

        //前置更新
        self::event('before_update', function ($model) {
            $model->update_time = date('Y-m-d H:i:s');

            return true;
        });
    }

    /**
     * 关联demoOne（一对一关系）
     * @author HuangYu
     * @since 2019/4/2
     * @return \think\model\relation\HasOne
     */
    public function demoOne()
    {
        return $this->hasOne('DemoOneModel', 'demo_id', 'id')
            ->field(['id', 'title']);
    }

    /**
     * 一对多关系
     * @author HuangYu
     * @since 2019/4/2
     * @return \think\model\relation\HasMany
     */
    public function demoMany()
    {
        return $this->hasMany('DemoManyModel', 'demo_id', 'id');
    }
}
